"""
     XBMC-TorrentBrowser
     Copyright 2011-2012 (C) Myrk0
    This addon is going to make browsing and downloading torrents easy and comfortable,
    at the moment the main goal is to make it general and start with PassthePopcorn and then
    moving over to Torrentleech, HDMI, SceneHD.org and more to come.
"""

import sys, xbmcaddon, xbmc, xbmcgui
import urllib, os

# Initializing Addon information
__version__ = "0.6.1"
__plugin__ = "TorrentBrowser " + __version__
__author__ = "Myrk0"
__url__ = "www.xbmc.com"

# Initialize XBMC and get settings
__settings__ = xbmcaddon.Addon( id='plugin.video.torrentbrowser' )
__language__ = __settings__.getLocalizedString
__deb__ = __settings__.getSetting( 'debug' ) == "true"

# When initiating something must be assigned to the global modules
__info__ = ""
__categories__ = ""
__tools__ = ""
__web__ = ""
__scraper__ = ""
__download__ = ""
__browser__ = ""
__xbmc__ = ""

if ( __name__ == "__main__" ):
    # Debug information
    if __deb__:
        print __plugin__ + 'default.py:: SYS.ARGV: ' + repr( sys.argv )
    else:
        print __plugin__

    import TBSites as sites
    __info__ = sites.getInfo( int( __settings__.getSetting( 'site' ) ) )
    __info2xbmc__ = sites.info2Xbmc()
    __categories__ = __info__['CATEGORIES']
    import TBTools as tools
    __tools__ = tools.TBTools()
    import TBWeb as web
    __web__ = web.TBWeb()
    import TBScraper as scraper
    __scraper__ = scraper.TBScraper()
    import TBDownload as download
    __download__ = download.TBDownload()
    import TBBrowser as browser
    __browser__ = browser.TBBrowser()
    import TBXbmc
    __xbmc__ = TBXbmc.TBXbmc()

    if ( not sys.argv[2] ):
        # If the program was just initiated, list categories
        __xbmc__.listCategories()
    else:
        params = __tools__.getParams( sys.argv[2] )
        get = params.get
        action = get( 'action' )
        if ( action == 'search' ) or ( action == 'get_movies' ) or ( action == 'get_formats' ) or ( action == 'further_search' ):
            if action == 'search':
                params['searchstring'] = __xbmc__.getUserInput( 'Search for movie', '' )
            __xbmc__.buildList( params )
        elif ( action == 'open_transmission'):
            xbmc.executebuiltin('XBMC.RunAddon(script.transmission)')            
        elif ( action == 'download' ):
                        
            sendToTransmissionResult = 0
            useMagnets = __settings__.getSetting('transmission_use_magnets')
            
            if __deb__:
                print str(useMagnets)
                print str(__settings__.getSetting('transmission_rpc_usage'))
            
            if str(__settings__.getSetting('transmission_rpc_usage')) == '2':                    
                dialogSendToTransmission = xbmcgui.Dialog()
                question = __language__(10001)
                if str(useMagnets) == 'true':
                    question = __language__(10004)
                sendToTransmissionResult = dialogSendToTransmission.yesno(__language__(10000), question)
            elif str(__settings__.getSetting('transmission_rpc_usage')) == '0':
                sendToTransmissionResult = 1
            
            if __deb__:
                print __plugin__ + 'default.py:: sendToTransmissionResult: ' + str(sendToTransmissionResult)
                        
            dlurl = urllib.unquote_plus( get( 'dlurl' ) )
            filename = urllib.unquote_plus( get( 'filename' ) )
            magnetUrl = ''
            if str(useMagnets) == 'true':
                magnetUrl = urllib.unquote_plus( get( 'magneturl' ) )
            __download__.downloadTorrent( urllib.unquote_plus( get( 'dlurl' ) ), urllib.unquote_plus( get( 'filename' ) ), sendToTransmissionResult, magnetUrl)
            
            if __settings__.getSetting( 'downloadSubs' ) == 'true':
                subscount = int(urllib.unquote_plus( get( 'subscount' ) ))
                for curIndex in range(subscount):
                    curSubLink = urllib.unquote_plus( get( 'subdlurl%s' % (str(curIndex)) ) )
                    curSubSiteIndex = int(urllib.unquote_plus( get( 'subsiteindex%s' % (str(curIndex)) ) ))
                    __download__.downloadSubtitles(curSubLink, curSubSiteIndex, urllib.unquote_plus( get( 'filename' ) ) )
            
            __xbmc__.showNotification( 'Download Started', filename, 4 )